package com.topway.dsmflex.ui.composite.synchro;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.CheckboxCellEditor;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.DialogCellEditor;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.jdom.JDOMException;

import com.Application;
import com.Consts;
import com.swtdesigner.SWTResourceManager;
import com.topway.dsmflex.Alert;
import com.topway.dsmflex.Log;
import com.topway.dsmflex.model.synchro.DataColumnBean;
import com.topway.dsmflex.model.synchro.DataSourceBean;
import com.topway.dsmflex.model.synchro.DataTableBean;
import com.topway.dsmflex.services.synchro.TableServices;
import com.topway.dsmflex.thread.services.SynchroServices;
import com.topway.dsmflex.ui.InitFormComposite;
import com.topway.dsmflex.ui.contentProvider.TableContentProvider;
import com.topway.dsmflex.ui.contentProvider.ViewContentProvider;
import com.topway.dsmflex.ui.dialog.ExpressionDialog;
import com.topway.dsmflex.ui.labelProvider.ConnNameProvider;
import com.topway.dsmflex.ui.labelProvider.TableNameProvider;
import com.topway.dsmflex.util.XmlEditUtil;



/**
 * Sql同步
 * 
 * 
 * @author liusy 2013-04-28
 *
 */
public class TableSynchro extends InitFormComposite {
	
   public static String name = "同步表设置";
   
   private static Logger log = Logger.getLogger(TableSynchro.class);
   
   private Shell shell;
   private Table         tblConn;
   private TableViewer   tvConn;
   private TableColumn   colConnName;
   private Composite     comLeft;
   private Table         tblTab;
   private CheckboxTableViewer   tvTab;
   private TableColumn   sourceTable;
   private Button btnStart;
   private TableViewer tvInputMeta ;
   private TableColumn   colOperator;
   private TableColumn colSourceOperator;
   private ComboBoxCellEditor comTargetTableName;
   private ComboBoxCellEditor comTargetColumnName;
   private ComboBoxCellEditor comTargetDs;
   
   private DataSourceBean dsSource;
   private DataTableBean  dt;
   private SynchroServices synchroServices = null;
   private TableServices tableServices = null;

   private String [] targetTables  = new String[]{};
   private String [] targetColumns  = new String[]{};
   private String [] targetSource = new String[]{};
   
   public TableSynchro(Composite parent, int style) {
      super(parent, style);
      createContents();
      initForm();
   }
   
   private void initConnection()
   {
	      try {
	    	  targetSource = XmlEditUtil.getDataSources();
	    	  tvConn.setInput(XmlEditUtil.readDataSourceXml().toArray());
			} catch (JDOMException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
   }

   public int initForm() {
	   this.synchroServices = SynchroServices.getSynchroServices();
	   this.tableServices = TableServices.getTableServices();
	   initConnection();
	   return 1;
   }

   protected void createContents() {
	   
	  shell = this.getShell();
      setLayout(new FillLayout());

      final SashForm sashForm = new SashForm(this, SWT.VERTICAL);
      sashForm.setLayout(new FillLayout());

      comLeft = new Composite(sashForm, SWT.NONE);
      comLeft.setLayout(new FormLayout());
	   
      final Group group = new Group(comLeft, SWT.NONE);
      group.setLayout(new FormLayout());
      final FormData fd_group = new FormData();
      fd_group.bottom = new FormAttachment(100, -1);
      fd_group.top = new FormAttachment(0, -5);
      fd_group.right = new FormAttachment(100, -1);
      fd_group.left = new FormAttachment(0, 1);
      group.setLayoutData(fd_group);

      tvConn = new TableViewer(group, SWT.BORDER | SWT.MULTI);
      tvConn.setContentProvider(new ViewContentProvider());
      tvConn.setLabelProvider(new ConnNameProvider());
      tblConn = tvConn.getTable();
      final FormData fd_tblConn = new FormData();
      fd_tblConn.bottom = new FormAttachment(100, -1);
      fd_tblConn.right = new FormAttachment(30, -1);
      fd_tblConn.left = new FormAttachment(0, 0);
      fd_tblConn.top = new FormAttachment(0, 0);
      tblConn.setLayoutData(fd_tblConn);
      tblConn.setLinesVisible(true);
      tblConn.setHeaderVisible(true);
      colConnName = new TableColumn(tblConn, SWT.NONE);
      colConnName.setWidth(268);
      colConnName.setText("连接名");
		tvConn.addDoubleClickListener(new IDoubleClickListener() {
			@Override
			public void doubleClick(DoubleClickEvent arg0) {
				IStructuredSelection obj = (IStructuredSelection) arg0.getSelection();
				dsSource = (DataSourceBean) obj.getFirstElement();
				List<DataTableBean> list = tableServices.getAllDataTable(dsSource);
				
				targetTables=tableServices.getSourceTable();
				comTargetTableName.setItems(targetTables);
				comTargetDs.setItems(targetSource);
				tvTab.setInput(list);
				DataTableBean _dt;
				for (int i = 0; i < list.size(); i++) {
					_dt = list.get(i);
					_dt.setName(_dt.getTableNameSource());
					if (_dt.getCheck()== 1)
						tvTab.setChecked(_dt, true);
				}
				tvInputMeta.setInput(null);
			}
		});
		
      tvTab = CheckboxTableViewer.newCheckList(group, SWT.BORDER | SWT.FULL_SELECTION);
      tvTab.setContentProvider(new TableContentProvider());
      tvTab.setLabelProvider(new TableNameProvider());
      tvTab.setColumnProperties(TABLE_INPUTMETAS);
      tblTab = tvTab.getTable();
      final FormData fd_tblTab = new FormData();
      fd_tblTab.bottom = new FormAttachment(100, -1);
      fd_tblTab.right = new FormAttachment(100, -1);
      fd_tblTab.left = new FormAttachment(tblConn, 0);
      fd_tblTab.top = new FormAttachment(0, 0);
      tblTab.setLayoutData(fd_tblTab);
      tblTab.setLinesVisible(true);
      tblTab.setHeaderVisible(true);
      CellEditor[] cellEditor = new CellEditor[8];
      cellEditor[0] = new CheckboxCellEditor(tblTab, SWT.NONE);
      cellEditor[1] = new ComboBoxCellEditor(tblTab, Consts.TABLE_ENABLED_LABEL, SWT.READ_ONLY);
      //cellEditor[2] = new TextCellEditor(tblTab, SWT.READ_ONLY);
      cellEditor[3] = new ComboBoxCellEditor(tblTab, Consts.TABLE_OPERATOR_LABEL, SWT.READ_ONLY);
      cellEditor[4] = new ComboBoxCellEditor(tblTab, Consts.TABLE_SOURCE_OPERATOR_LABEL, SWT.READ_ONLY);
      comTargetTableName= new ComboBoxCellEditor(tblTab, targetTables, SWT.READ_ONLY);
      cellEditor[5] = comTargetTableName;
      comTargetDs = new ComboBoxCellEditor(tblTab, targetSource, SWT.READ_ONLY);
      cellEditor[6] =comTargetDs;
      cellEditor[7]  =  new TextCellEditor(tblTab, SWT.NONE);
//      Text text1 = (Text)cellEditor[7] .getControl();
//      text1.addVerifyListener(new VerifyListener() {
//         public void verifyText(VerifyEvent e) {
//            String str = e.text;
//            if (str != null && str.length() > 0) e.doit = StringUtil.isInteger(str);
//         }
//      });
      tvTab.setCellEditors(cellEditor);
      tvTab.setCellModifier(new TabInputsCellModifier(tvTab));
      
      TableColumn   colTabCheck = new TableColumn(tblTab, SWT.CHECK);
      colTabCheck.setWidth(20);
      
      TableColumn  statu = new TableColumn(tblTab, SWT.NONE);
      statu.setWidth(40);
      statu.setText("激活");
      
      tblTab.setSortColumn(statu);
      statu.addSelectionListener(new SelectionAdapter(){
          public void widgetSelected(SelectionEvent e){
        	  tvTab.setSorter(new DataTableBeanViewerSorter(DataTableBeanViewerSorter.Enabled));
          }
      });
      
      sourceTable = new TableColumn(tblTab, SWT.NONE);
      sourceTable.setWidth(140);
      sourceTable.setText("源表名");
      
      statu.addSelectionListener(new SelectionAdapter(){
          public void widgetSelected(SelectionEvent e){
        	  tvTab.setSorter(new DataTableBeanViewerSorter(DataTableBeanViewerSorter.TableNameSource));
          }
      });
      
      colOperator = new TableColumn(tblTab, SWT.NONE);
      colOperator.setWidth(65);
      colOperator.setText("目标操作");
      
      colSourceOperator = new TableColumn(tblTab, SWT.NONE);
      colSourceOperator.setWidth(65);
      colSourceOperator.setText("源表操作");
 
      TableColumn targetTable = new TableColumn(tblTab, SWT.NONE);
      targetTable.setWidth(140);
      targetTable.setText("目标表");
      
      
      
      TableColumn targetSource = new TableColumn(tblTab, SWT.NONE);
      targetSource.setWidth(80);
      targetSource.setText("目标数据源");
      
      TableColumn synchroNterval = new TableColumn(tblTab, SWT.NONE);
      synchroNterval.setWidth(60);
      synchroNterval.setText("频率(分)");
 
      tvTab.addDoubleClickListener(new IDoubleClickListener() {
		@Override
		public void doubleClick(DoubleClickEvent arg0) {
			   List<DataColumnBean> listInput = (List<DataColumnBean>) tvInputMeta.getInput();
			   if(null !=listInput && listInput.size()!=0)
		        	 dt.setDataColumnBean(listInput);

			IStructuredSelection obj = (IStructuredSelection)arg0.getSelection();
			   dt = (DataTableBean) obj.getFirstElement();
		            try {
		            	List<DataColumnBean> list = dt.getDataColumnBean();
		            	if(null==list||list.size()==0)//不读从数据库中获取最新的字段信息
		            		list = (List<DataColumnBean>) tableServices.getColumnInfo(dt);
		            	targetColumns =  tableServices.getColumnInfoArray(dt);
					    	  comTargetColumnName.setItems(targetColumns);
					      
					      if(!dt.getTableNameSource().equals(dt.getTableNameTarget()))
					      {
					    	  for (DataColumnBean _dc : list) {
					    		  for (int i = 0; i < targetColumns.length; i++) {
					    			  if(_dc.getColumnNameTarget().equals(targetColumns[i]))
					    			  {
					    				  _dc.setColumnNameTarget(targetColumns[i]);
					    				  break;
					    			  }else if(!_dc.getColumnNameTarget().equals("")&& !_dc.getColumnNameTarget().equals(targetColumns[i]))
					    			  {
					    				 break;
					    			  }else
					    				  _dc.setColumnNameTarget("");
									}  
					    	  }
					      }
					      
		            	tvInputMeta.setInput(list);
					} catch (Exception e) {
						e.printStackTrace();
						log.error(e.getMessage());
					}	
		}
	});
      
      final Composite composite_right = new Composite(sashForm, SWT.NONE);
      composite_right.setLayout(new FormLayout());

      final Group group_right= new Group(composite_right, SWT.NONE);
      final FormData fd_group_right = new FormData();
      fd_group_right.left = new FormAttachment(0, 1);
      fd_group_right.bottom = new FormAttachment(100, -1);
      fd_group_right.right = new FormAttachment(100, -1);
      fd_group_right.top = new FormAttachment(0, -5);
      group_right.setLayoutData(fd_group_right);
      group_right.setLayout(new FormLayout());
      
      tvInputMeta = new TableViewer(group_right, SWT.FULL_SELECTION | SWT.BORDER);
      tvInputMeta.setContentProvider(new TableContentProvider());
      tvInputMeta.setLabelProvider(new InputMetaLabelProvider());
      tvInputMeta.setColumnProperties(INPUTMETAS);
      Table tblInputMeta = tvInputMeta.getTable();
      final FormData fd_tblInputMeta = new FormData();
      fd_tblInputMeta.bottom = new FormAttachment(90, 0);
      fd_tblInputMeta.right = new FormAttachment(100, 0);
      fd_tblInputMeta.top = new FormAttachment(0, 0);
      fd_tblInputMeta.left = new FormAttachment(0, 0);
      tblInputMeta.setLayoutData(fd_tblInputMeta);
      tblInputMeta.setLinesVisible(true);
      tblInputMeta.setHeaderVisible(true);
      CellEditor[] cellEditor2 = new CellEditor[8];
      cellEditor2[0] = new TextCellEditor(tblInputMeta, SWT.READ_ONLY);
      cellEditor2[1] = new ComboBoxCellEditor(tblInputMeta, Consts.OPERATOR_LABEL, SWT.READ_ONLY);
      cellEditor2[2] = new TextCellEditor(tblInputMeta, SWT.NONE);
      cellEditor2[3] = new ComboBoxCellEditor(tblInputMeta,Consts.ANDOR_LABEL, SWT.READ_ONLY);
      cellEditor2[4] = new TextCellEditor(tblInputMeta, SWT.NONE);
      cellEditor2[5] = new ComboBoxCellEditor(tblInputMeta,Consts.TABLE_KEY_LABEL, SWT.READ_ONLY);
      comTargetColumnName = new ComboBoxCellEditor(tblInputMeta,targetColumns, SWT.READ_ONLY);
      cellEditor2[6] =comTargetColumnName;
      cellEditor2[7] = new ExpressionCellEditor(tblInputMeta);
     
      tvInputMeta.setCellEditors(cellEditor2);
      tvInputMeta.setCellModifier(new InputsCellModifier(tvInputMeta));

      final TableColumn colNameSource = new TableColumn(tblInputMeta, SWT.NONE);
      colNameSource.setWidth(110);
      colNameSource.setText("源字段名");

      final TableColumn colOper1 = new TableColumn(tblInputMeta, SWT.NONE);
      colOper1.setWidth(60);
      colOper1.setText("操作符");

      final TableColumn inputValue = new TableColumn(tblInputMeta, SWT.NONE);
      inputValue.setWidth(150);
      inputValue.setText("值");

      final TableColumn colOutput1 = new TableColumn(tblInputMeta, SWT.NONE);
      colOutput1.setWidth(50);
      colOutput1.setText("条件");
      

      final TableColumn colUpdateValue = new TableColumn(tblInputMeta, SWT.NONE);
      colUpdateValue.setWidth(70);
      colUpdateValue.setText("更新状态");

      final TableColumn colIsKey = new TableColumn(tblInputMeta, SWT.NONE);
      colIsKey.setWidth(70);
      colIsKey.setText("主键");


      final TableColumn colNameTarget = new TableColumn(tblInputMeta, SWT.NONE);
      colNameTarget.setWidth(110);
      colNameTarget.setText("目标字段名");
      
	    final TableColumn colExpress = new TableColumn(tblInputMeta, SWT.NONE);
	    colExpress.setWidth(150);
	    colExpress.setText("表达式");
      
      
      Button btnSvae = new Button(group_right, SWT.NONE);
   //   btnSvae.setAlignment(SWT.LEFT);
      btnSvae.addSelectionListener(new SelectionAdapter() {
         public void widgetSelected(final SelectionEvent e) {
			   List<DataColumnBean> listInput = (List<DataColumnBean>) tvInputMeta.getInput();
			   if(null !=listInput && listInput.size()!=0)
		        	 dt.setDataColumnBean(listInput);
			   
        	 Object [] obj = (Object[]) tvTab.getCheckedElements();
        	 List<DataTableBean> list = new ArrayList<DataTableBean>();
        	 for (int i = 0; i < obj.length; i++) {
				list.add((DataTableBean) obj[i]);
			}
     	 	tableServices.saveTableConfigList(list);
           	 if(list.size()>0)
           	 {
           	 	Log.clearLog();
           	 	//Alert.MsgBox("提示", "保存成功");
           	 	Application.openMenu(SystemLog.name);
           	 }
         }
      });
      
      btnSvae.setImage(SWTResourceManager.getImage(Application.class, "/img/savesetting.gif"));
      final FormData fd_btnLoad = new FormData();
      fd_btnLoad.left = new FormAttachment(50, -30);
      fd_btnLoad.bottom = new FormAttachment(100, -5);
      fd_btnLoad.width = 70;
      btnSvae.setLayoutData(fd_btnLoad);
      btnSvae.setFont(SWTResourceManager.getFont("", 10, SWT.BOLD));
      btnSvae.setText("编译");
      btnSvae.setToolTipText("编译并保存，如未通过，日志将以红色字体提示");
      
//      btnStart = new Button(group_right, SWT.NONE);
//      fd_btnLoad.bottom = new FormAttachment(btnStart, 0, SWT.BOTTOM);
// 
//      btnStart.addSelectionListener(new SelectionAdapter() {
//         public void widgetSelected(final SelectionEvent e) {
//        	 synchroMonitor.start(5);
//        	 btnStart.setEnabled(false);
//         }
//      });
//      btnStart.setImage(SWTResourceManager.getImage(Application.class, "/img/start.png"));
//      final FormData fd_btnCancel = new FormData();
//      fd_btnCancel.left = new FormAttachment(50, 15);
//      fd_btnCancel.bottom = new FormAttachment(100, -5);
//      fd_btnCancel.width = 70;
//      //fd_btnCancel.height = 26;
//      btnStart.setLayoutData(fd_btnCancel);
//      btnStart.setFont(SWTResourceManager.getFont("", 10, SWT.BOLD));
//      btnStart.setText("启动");

      sashForm.setWeights(new int []{2,5});

   }
   


   
   class InputMetaLabelProvider extends LabelProvider implements ITableLabelProvider {
	      public String getColumnText(Object obj, int columnIndex) {
	    	  DataColumnBean dsi = (DataColumnBean )  obj;
	         switch (columnIndex) {
	         case 0:
	            return dsi.getColumnNameSource();
	         case 1:
	            return getLabel(Consts.OPERATOR_LABEL,Consts.OPERATOR,dsi.getOperator());
	         case 2:
	        	 return dsi.getInputValue();
	         case 3:
	        	 return getLabel(Consts.ANDOR_LABEL,Consts.ANDOR,dsi.getLogic());
	         case 4:
	        	 return dsi.getUpdateValue();
	         case 5:
	        	 return getLabel(Consts.TABLE_KEY_LABEL,Consts.TABLE_KEY,dsi.getIsKey());
	         case 6:
	        	 return dsi.getColumnNameTarget();
	         case 7:
	        	 return dsi.getColExpress();
	         }
	         return null;
	      }

	      private String getLabel(String[] labels, String[] values, String name) {
	         for (int i = 0; i < values.length; i++) {
	            if (values[i].equalsIgnoreCase(name)) return labels[i];
	         }
	         return "";
	      }

	      public String getText(Object element) {
	         return element == null ? "" : element.toString();
	      }

	      public Image getColumnImage(Object obj, int index) {
	         return null;
	      }
	   }

	   public static String[] INPUTMETAS = new String[] { "columnNameSource", "operator", "inputValue","logic","updateValue","isKey" ,"columnNameTarget","colExpress"};
	   public static String[] TABLE_INPUTMETAS = new String[] { "check","enabled","tableNameSource", "operatorTarget", "operatorSource","tableNameTarget","targetSource","synchroNterval"};


	   class InputsCellModifier implements ICellModifier {
	      private TableViewer tv;

	      public InputsCellModifier(TableViewer tv) {
	         this.tv = tv;
	      }

	      public boolean canModify(Object element, String property) {
	         return true;
	      }

	      public Object getValue(Object element, String property) {
	    	  DataColumnBean o = (DataColumnBean ) element;
	        if (property.equals("operator")) return getIndex(Consts.OPERATOR, o.getOperator());
	        else if (property.equals("logic")) return getIndex(Consts.ANDOR, o.getLogic());
	        else if (property.equals("isKey")) return getIndex(Consts.TABLE_KEY, o.getIsKey());
	        else if (property.equals("columnNameSource")) return o.getColumnNameSource();
	        else if (property.equals("columnNameTarget"))
	        	{
		        		 return getIndex(targetColumns, o.getColumnNameTarget());
	        	}
	        else if (property.equals("inputValue")) return (null==o.getInputValue()?"":o.getInputValue());//值为空时出现断言，isTrue错错误
	        else if (property.equals("updateValue")) return (null==o.getUpdateValue()?"":o.getUpdateValue());//值为空时出现断言，isTrue错错误
	        else if (property.equals("colExpress")) return (null==o.getColExpress()?"":o.getColExpress());
	        throw new RuntimeException("错误的列别名:" + property);
	      }

	      private int getIndex(String[] labels, String name) {
	         for (int i = 0; i < labels.length; i++) {
	            if (labels[i].equalsIgnoreCase(name)) return i;
	         }
	         return 0;
	      }

	      public void modify(Object element, String property, Object value) {
	         TableItem item = (TableItem) element;
	         DataColumnBean o = (DataColumnBean ) item.getData();
	         if (property.equals("operator")) {
		            o.setOperator(Consts.OPERATOR[(Integer) value]);
		         }
	         else  if (property.equals("logic")) {
		            o.setLogic(Consts.ANDOR[(Integer) value]);
		         }
	         else  if (property.equals("isKey")) {
		            o.setIsKey(Consts.TABLE_KEY[(Integer) value]);
		         }
	         else  if (property.equals("columnNameSource")) {
		            o.setColumnNameSource((String) value);
			     }
	         else  if (property.equals("columnNameTarget")) {
		        		 o.setColumnNameTarget(targetColumns[(Integer) value]);
	        	}
	         else  if (property.equals("updateValue")) {
		            o.setUpdateValue((String) value);
			     }
	         else  if (property.equals("inputValue")) {
		            o.setInputValue((String) value);
			     }
	         else  if (property.equals("colExpress")) {
		            o.setColExpress((String) value);
			     }
	         else {
	             throw new RuntimeException("错误的列别名:" + property);
	          }
	         tv.update(o, null);
	      }
	   }
	   class TabInputsCellModifier implements ICellModifier {
		      private CheckboxTableViewer tv;

		      public TabInputsCellModifier(CheckboxTableViewer tv) {
		         this.tv = tv;
		      }

		      public boolean canModify(Object element, String property) {
		         return true;
		      }

		      public Object getValue(Object element, String property) {
		    	  DataTableBean o = (DataTableBean ) element;
		    	  if (property.equals("enabled")) return getIndex(Consts.TABLE_ENABLED, ""+o.getEnabled());
		    	  else if (property.equals("operatorTarget")) return getIndex(Consts.TABLE_OPERATOR, o.getOperatorTarget());
		        else if(property.equals("operatorSource"))return getIndex(Consts.TABLE_SOURCE_OPERATOR, o.getOperatorSource());
		        else if(property.equals("targetSource"))return getIndex(targetSource, o.getDsTarget());
		        else if(property.equals("tableNameSource"))return o.getTableNameSource();
		        else if(property.equals("tableNameTarget")) return getIndex(targetTables, o.getTableNameTarget());
		        else if(property.equals("synchroNterval")) return  String.valueOf(o.getSynchroNterval());
		        throw new RuntimeException("错误的列别名:" + property);
		      }

		      private int getIndex(String[] labels, String name) {
		         for (int i = 0; i < labels.length; i++) {
		            if (labels[i].equalsIgnoreCase(name)) return i;
		         }
		         return 0;
		      }

		      public void modify(Object element, String property, Object value) {
		         TableItem item = (TableItem) element;
		         DataTableBean o = (DataTableBean ) item.getData();
		         if (property.equals("operatorTarget")) {
			            o.setOperatorTarget(Consts.TABLE_OPERATOR[(Integer) value]);
			         } else if(property.equals("operatorSource")){
			        	 o.setOperatorSource(Consts.TABLE_SOURCE_OPERATOR[(Integer) value]);
			         } else if(property.equals("tableNameSource")){
			        	 o.setTableNameSource((String) value);
			         }   else if(property.equals("enabled")){
			        	 o.setEnabled(Integer.valueOf(Consts.TABLE_ENABLED[(Integer) value]));
			         } else if(property.equals("synchroNterval")){
			        	 float v=o.getSynchroNterval();
			        	 try {
			        		 v=Float.parseFloat((String) value);
						} catch (Exception e) {
							Alert.MsgBox("错误", (String) value+"错误！！");
						}
			        	 o.setSynchroNterval(v);
			         }else if(property.equals("tableNameTarget")){
			        	 try {
			        		 o.setTableNameTarget(targetTables[(Integer) value]);
			                	targetColumns =  tableServices.getColumnInfoArray(o);
						    	  comTargetColumnName.setItems(targetColumns);
						} catch (ArrayIndexOutOfBoundsException e) {
						}
			         }else if(property.equals("targetSource")){
			        	 o.setDsTarget(targetSource[(Integer) value]);
//			 			IStructuredSelection obj = (IStructuredSelection)tvTab.getSelection();
//						   dt = (DataTableBean) obj.getFirstElement();
						targetTables =  tableServices.getTargetTablesByDb(o);
					    	  comTargetTableName.setItems(targetTables);
			         }
			         else {
			             throw new RuntimeException("错误的列别名:" + property);
			          }
		         tv.update(o, null);
		      }
		   }
	   
	   
	   class ExpressionCellEditor extends DialogCellEditor {

		      private Table table;

		      public ExpressionCellEditor(Composite parent) {
		         super(parent);
		         this.table = (Table) parent;
		      }
		      protected Object openDialogBox(Control cellEditorWindow) {
		         TableItem[] selectItems = table.getSelection();
		         String exp = "";
		         if (selectItems != null && selectItems.length > 0) exp = ((DataColumnBean) selectItems[0].getData()).getColExpress();
		         ExpressionDialog gcd = new ExpressionDialog(cellEditorWindow.getShell(), null==exp?"":exp);
		         String res = gcd.open();
		         return res;
		      }
		   }
	   
	   class DataTableBeanViewerSorter extends ViewerSorter {
		      private static final int Enabled = 1;
		        private static final int TableNameSource = 2;
		        private static final int TableNameTarget = 3;
		        
		        private int sortType ;
		        private DataTableBeanViewerSorter(int sortType){
		            this.sortType = sortType;
		        }
		@Override
		public int compare(Viewer viewer, Object e1, Object e2) {
			DataTableBean p1 = (DataTableBean)e1;
			DataTableBean p2 = (DataTableBean)e2;
			if(sortType==Enabled)
			{
				if(p1.getEnabled()>p2.getEnabled())
				return 1;
			}
			else if(sortType==TableNameSource)
				return p1.getTableNameSource().compareTo(p2.getTableNameSource());
			else if(sortType==TableNameTarget)
				return p1.getTableNameTarget().compareTo(p2.getTableNameTarget());
			return 0;
		}

		   }
	   
	   
}
